import React, {PureComponent} from "react";
import {Column, Line, Pie, measureTextWidth} from '@ant-design/plots';
import {connect} from "react-redux";
import {query} from "./actions";
import {Button, Card, notification} from "antd";
import {getCurrentOrganization, getLastFilter, getOpenFollow, getPrincipal} from "../../lib/identity";
import moment from "moment";
import lodash from 'lodash';

const LAST_FILTER = "zadOrderAnal";

class List extends PureComponent {

    componentWillMount() {
        const {dispatch} = this.props;
        let fields = getLastFilter(LAST_FILTER);
        if (fields === null || fields === undefined) {
            fields = {};
        }
        dispatch(query({...fields, "year": moment().year().toString(), "organizationId": getCurrentOrganization()}));
    };


    exportFile = (fileName, fileData) => {
        document.getElementById("fileName").value = fileName;
        if (fileData && fileData.length > 0) {
            const headers = [];
            fileData.forEach(item => {
                for (let key in item) {
                    if (headers.indexOf(key) <= -1) {
                        headers.push(key);
                    }
                }
            });
            document.getElementById("headers").value = lodash.join(headers, ',');
            document.getElementById("rows").value = JSON.stringify(fileData);
            document.getElementById("exportFile").submit();
            notification.success({
                message: '请等待文件导出'
            });
        } else {
            notification.error({
                message: '没有数据可以导出'
            });
        }
    };

    render() {
        const {
            result, loading,
        } = this.props;

        const bgData = [];
        const bgList = result['bgList'] || [];
        bgList.forEach((item, index) => {
            bgData.push({"名称": item.name, "总数": item.count});
        });
        const kaData = [];
        const kaList = result['kaList'] || [];
        kaList.forEach((item, index) => {
            kaData.push({"名称": item.name, "总数": item.count});
        });
        const bgConfig = {
            data: bgData, xField: '名称', yField: '总数', label: {
                // 可手动配置 label 数据标签位置
                position: 'middle', // 'top', 'bottom', 'middle',
                // 配置样式
                style: {
                    fill: '#FFFFFF', opacity: 0.6,
                },
            }, xAxis: {
                label: {
                    autoHide: true, autoRotate: false,
                },
            }, meta: {
                type: {
                    alias: '报关方式',
                }, sales: {
                    alias: '总数',
                },
            },
        };
        const kaConfig = {
            data: kaData, xField: '名称', yField: '总数', label: {
                // 可手动配置 label 数据标签位置
                position: 'middle', // 'top', 'bottom', 'middle',
                // 配置样式
                style: {
                    fill: '#FFFFFF', opacity: 0.6,
                },
            }, xAxis: {
                label: {
                    autoHide: true, autoRotate: false,
                },
            }, meta: {
                type: {
                    alias: '口岸',
                }, sales: {
                    alias: '总数',
                },
            }
        };
        const orderCount = [];
        const sameStartPlaceList = result['sameStartPlaceList'] || [];
        sameStartPlaceList.forEach((item, index) => {
            const dataList = item['endList'] || [];
            dataList.forEach((endItem, index) => {
                orderCount.push({"起始站": item['startPlace'], "名称": endItem.name, "总数": endItem.count});
            });
        });
        const orderCountConfig = {
            data: orderCount, xField: '名称', yField: '总数', seriesField: '起始站', isGroup: true, columnStyle: {
                radius: [20, 20, 0, 0],
            }
        };
        const lineAgeData = [];
        const lineAgeList = result['lineAgeList'] || [];
        lineAgeList.forEach((item, index) => {
            lineAgeData.push({"月份": item.month + "月", "线路": item.line, "时效": item.ratio});
        });
        const lineAgeDataConfig = {
            data: lineAgeData, xField: '月份', yField: '时效', seriesField: '线路', yAxis: {
                label: {
                    formatter: (v) => `${v}`,
                },
            }, legend: {
                position: 'top',
            }, smooth: true, animation: {
                appear: {
                    animation: 'path-in', duration: 5000,
                },
            },
        };

        // SOC COC 租箱
        const renderStatistic = (containerWidth, text, style) => {
            const {width: textWidth, height: textHeight} = measureTextWidth(text, style);
            const R = containerWidth / 2; // r^2 = (w / 2)^2 + (h - offsetY)^2

            let scale = 1;

            if (containerWidth < textWidth) {
                scale = Math.min(Math.sqrt(Math.abs(Math.pow(R, 2) / (Math.pow(textWidth / 2, 2) + Math.pow(textHeight, 2)))), 1);
            }

            const textStyleStr = `width:${containerWidth}px;`;
            return `<div style="${textStyleStr};font-size:${scale}em;line-height:${scale < 1 ? 1 : 'inherit'};">${text}</div>`;
        };
        const soccocData = [];
        const soccocDataSource = result['soccocCountDto'] || {};
        soccocData.push({"type": "SOC", "value": soccocDataSource['socCount']});
        soccocData.push({"type": "COC", "value": soccocDataSource['cocCount']});
        soccocData.push({"type": "租箱", "value": soccocDataSource['zxCount']});
        const soccocConfig = {
            appendPadding: 10,
            data: soccocData,
            angleField: 'value',
            colorField: 'type',
            radius: 1,
            innerRadius: 0.64,
            meta: {
                value: {
                    formatter: (v) => `${v}`,
                },
            },
            label: {
                type: 'inner', offset: '-50%', style: {
                    textAlign: 'center',
                }, autoRotate: false, content: '{value}',
            },
            statistic: {
                title: {
                    offsetY: -4, customHtml: (container, view, datum) => {
                        const {width, height} = container.getBoundingClientRect();
                        const d = Math.sqrt(Math.pow(width / 2, 2) + Math.pow(height / 2, 2));
                        const text = datum ? datum.type : '总计';
                        return renderStatistic(d, text, {
                            fontSize: 28,
                        });
                    },
                }, content: {
                    offsetY: 4, style: {
                        fontSize: '32px',
                    }, customHtml: (container, view, datum, data) => {
                        const {width} = container.getBoundingClientRect();
                        const text = datum ? `${datum.value}` : `${data.reduce((r, d) => r + d.value, 0)}`;
                        return renderStatistic(width, text, {
                            fontSize: 32,
                        });
                    },
                },
            }, // 添加 中心统计文本 交互
            interactions: [{
                type: 'element-selected',
            }, {
                type: 'element-active',
            }, {
                type: 'pie-statistic-active',
            },],
        };
        // 货物品类
        const categoryData = [];
        const categoryDataSource = result['plList'] || [];
        categoryDataSource.forEach((item, index) => {
            categoryData.push({"name": item.name, "value": item.count});
        });
        const goodsConfig = {
            appendPadding: 10, data: categoryData, angleField: 'value', colorField: 'name', radius: 0.8, label: {
                type: 'outer', content: '{name} {percentage}',
            }, interactions: [{
                type: 'pie-legend-active',
            }, {
                type: 'element-active',
            },],
        };
        // 租箱点
        const zxdData = [];
        const zxdDataSource = result['zxdList'] || [];
        zxdDataSource.forEach((item, index) => {
            zxdData.push({"name": item.name, "value": item.count});
        });
        const zxdConfig = {
            appendPadding: 10, data: zxdData, angleField: 'value', colorField: 'name', radius: 0.8, label: {
                type: 'outer', content: '{name} {percentage}',
            }, interactions: [{
                type: 'pie-legend-active',
            }, {
                type: 'element-active',
            },],
        };
        // 归还状态
        const returnData = [];
        const returndDataSource = result['returnList'] || [];
        returndDataSource.forEach((item, index) => {
            returnData.push({"name": item.name, "value": item.count});
        });
        const returnConfig = {
            appendPadding: 10, data: returnData, angleField: 'value', colorField: 'name', radius: 0.8, label: {
                type: 'outer', content: '{name} {percentage}',
            }, interactions: [{
                type: 'pie-legend-active',
            }, {
                type: 'element-active',
            },],
        };
        return (<div>
            <div className="line1">
                <Card style={{width: "25%", float: "left"}}
                      title="报关方式 单位：票" extra={<Button onClick={() => this.exportFile("报关方式", bgData)}>导出</Button>}>
                    <Column {...bgConfig} />
                </Card>
                <Card style={{width: "25%", float: "left", marginLeft: "10px"}}
                      title="口岸 单位：票" extra={<Button onClick={() => this.exportFile("口岸", kaData)}>导出</Button>}>
                    <Column {...kaConfig} />
                </Card>
                <Card style={{width: "45%", float: "left", marginLeft: "10px"}}
                      title="订单数 单位：票" extra={<Button onClick={() => this.exportFile("订单数", orderCount)}>导出</Button>}>
                    <Column {...orderCountConfig} />
                </Card>
            </div>
            <div className="line2">
                <Card style={{width: "100%", float: "left"}}
                      title="平均时效 行驶天">
                    <Line {...lineAgeDataConfig} />
                </Card>
            </div>
            <div className="line2">
                <Card style={{width: "25%", float: "left"}}
                      title="SOC、COC、租箱 单位：票"
                      extra={<Button onClick={() => this.exportFile("SOC、COC、租箱", soccocData)}>导出</Button>}>
                    <Pie {...soccocConfig} />
                </Card>
                <Card style={{width: "25%", float: "left"}}
                      title="货物品类 单位：票"
                      extra={<Button onClick={() => this.exportFile("货物品类", categoryData)}>导出</Button>}>
                    <Pie {...goodsConfig} />
                </Card>
                <Card style={{width: "25%", float: "left"}}
                      title="租箱点 单位：票" extra={<Button onClick={() => this.exportFile("租箱点", zxdData)}>导出</Button>}>
                    <Pie {...zxdConfig} />
                </Card>
                <Card style={{width: "25%", float: "left"}}
                      title="归还状态 单位：票" extra={<Button onClick={() => this.exportFile("归还状态", returnData)}>导出</Button>}>
                    <Pie {...returnConfig} />
                </Card>
            </div>
            <form
                id="exportFile"
                method="post"
                target="_blank"
                action="/api/orderAnalysis/commonExport"
            >
                <input
                    name="fileName"
                    type="hidden"
                    id="fileName"
                />
                <input
                    id="rows"
                    name="rows"
                    type="hidden"
                />
                <input
                    id="headers"
                    name="headers"
                    type="hidden"
                />
            </form>
        </div>);
    }
}

const mapStateToProps = state => {
    return {
        ...state.zadOrderAnal.list
    };
};

export default connect(mapStateToProps)(List);
